package com.ykc.proxy;

import com.ykc.helper.DatabaseHelper;
import com.ykc.spring.Transactional;

import java.lang.reflect.Method;

public class TransactionProxy implements Proxy {

    @Override
    public Object doProxy(ProxyChain proxyChain) throws Throwable {
        Object result;
        Method method=proxyChain.getTargetMethod();
        //加入了Transactional的方法要做事务处理
        if (method.isAnnotationPresent(Transactional.class)){
            try {
                DatabaseHelper.beginTransaction();
                System.out.println("开启事务");
                result=proxyChain.doProxyChain();
                DatabaseHelper.commitTransaction();
                System.out.println("提交事务");
            }catch (Exception e){
                DatabaseHelper.rollbackTransaction();
                System.out.println("事务回滚");
                throw e;
            }
        }else{
            result=proxyChain.doProxyChain();
        }

        return result;
    }
}
